import React, { useRef, useEffect } from 'react';
import { Range, Editor } from 'slate';
import { useSlate, ReactEditor } from 'slate-react';
import { css } from 'emotion';

import { Portal } from '../../component';

import { MarkButton, LinkButton } from './Button';

export const HoveringToolbar = () => {
  const ref = useRef<HTMLDivElement | null>(null);
  const editor = useSlate();

  useEffect(() => {
    const el = ref.current;
    const { selection } = editor;

    if (!el) {
      return;
    }

    if (!selection || !ReactEditor.isFocused(editor) || Range.isCollapsed(selection) || Editor.string(editor, selection) === '') {
      el.removeAttribute('style');
      return;
    }

    const domSelection = window.getSelection();
    if (!domSelection) return;
    const domRange = domSelection.getRangeAt(0);
    const rect = domRange.getBoundingClientRect();
    el.style.opacity = '1';
    el.style.top = `${rect.top + window.pageYOffset - el.offsetHeight}px`;
    el.style.left = `${rect.left}px`;
  });

  return (
    <Portal>
      <div
        ref={ref}
        className={css`
          top: -10000px;
          left: -10000px;
          padding: 2px;
          position: absolute;
          z-index: 1;
          margin-top: -6px;
          opacity: 0;
          background-color: #fff;
          border-radius: 4px;
          -webkit-transition: opacity 0.75s;
          transition: opacity 0.75s;
          border: #222 solid 1px;
          display: flex;

          * + * {
            margin-left: 2px;
          }
        `}
      >
        <MarkButton format="bold" icon="bold" />
        <MarkButton format="italic" icon="italic" />
        <MarkButton format="underline" icon="underline" />
        <MarkButton format="strike" icon="strike" />
        <LinkButton />
      </div>
    </Portal>
  );
};
